package com.bnyy.medicalHousekeeper.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.SpanUtils;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AAChartModel;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AAChartView;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AAMoveOverEventMessageModel;
import com.bnyy.common.view.AAChartCoreLib.AAChartCreator.AASeriesElement;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartStackingType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartSymbolStyleType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartSymbolType;
import com.bnyy.common.view.AAChartCoreLib.AAChartEnum.AAChartType;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAMarker;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAOptions;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AASeries;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AASeriesEvents;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAStyle;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AATooltip;
import com.bnyy.common.view.AAChartCoreLib.AAOptionsModel.AAYAxis;
import com.bnyy.common.view.AAChartCoreLib.AATools.AAColor;
import com.bnyy.common.view.AAChartCoreLib.AATools.AAGradientColor;
import com.bnyy.common.view.AAChartCoreLib.AATools.AALinearGradientDirection;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseFragmentImpl;
import com.bnyy.medicalHousekeeper.bean.BloodPressDetail;
import com.bnyy.medicalHousekeeper.bean.HealthDataDetail;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.google.gson.Gson;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2023/2/14
 **/
public class HealthDataDetailFragment extends BaseFragmentImpl {
    @BindView(R.id.iv_previous)
    ImageView ivPrevious;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.iv_next)
    ImageView ivNext;
    @BindView(R.id.tv_select_date)
    TextView tvSelectDate;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.tv_max)
    TextView tvMax;
    @BindView(R.id.tv_min)
    TextView tvMin;
    @BindView(R.id.aa_chart_view)
    AAChartView aaChartView;

    private int type;
    private int wearId;
    private int index = 0;

    public static HealthDataDetailFragment getInstance(int wearId, int type) {

        HealthDataDetailFragment fragment = new HealthDataDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("wearId", wearId);
        bundle.putInt("type", type);
        fragment.setArguments(bundle);

        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_health_data_detail;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getInt("type", -1);
            wearId = bundle.getInt("wearId", -1);

            getHealthData();
        }

        ivPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index++;
                getHealthData();
            }
        });

        ivNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index--;
                getHealthData();
            }
        });

        aaChartView.callBack = new AAChartView.AAChartViewCallBack() {
            @Override
            public void chartViewDidFinishLoad(AAChartView aaChartView) {

            }

            @Override
            public void chartViewMoveOverEventMessage(AAChartView aaChartView, AAMoveOverEventMessageModel messageModel) {
                Log.e("chartViewMoveOverEventMessage", new Gson().toJson(messageModel.offset));

                ArrayList<String> tag = (ArrayList<String>) aaChartView.getTag();

                String unit = "";
                switch (type) {
                    case 0:
                        unit = "bpm";
                        break;
                    case 3:
                        unit = "mmHg";
                        break;
                    case 4:
                        unit = "%";
                        break;
                }

                tvSelectDate.setText(messageModel.category);

                SpanUtils.with(tvData)
                        .append(tag.get(messageModel.x.intValue())).setBold()
                        .append(unit).setFontSize(12, true)
                        .create();
            }
        };
    }

    private void getHealthData() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("wear_id", wearId);
        params.put("type", type);
        params.put("scope", "week");
        params.put("index", index);

        if (type == 3) {
            requestManager.request(requestManager.mJavaRetrofitService.getBloodPressDetail(RequestManager.getJsonRequestBody(params)),
                    new BaseObserverImpl<BloodPressDetail>(mContext) {
                        @Override
                        public void onSuccess(BloodPressDetail bloodPressDetail) {
                            super.onSuccess(bloodPressDetail);
                            int highMax = 0;
                            int highMin = 0;
                            int lowMax = 0;
                            int lowMin = 0;
                            String unit = "mmHg";

                            ArrayList<BloodPressDetail.BloodPressData> datas = bloodPressDetail.getDatas();

                            int size = datas.size();

                            if (size > 0) {
                                setDate(datas.get(0).getDt(), datas.get(size - 1).getDt());
                            }
                            ArrayList<String> tag = new ArrayList<>();
                            Object[] highDatas = new Object[size];
                            Object[] lowDatas = new Object[size];
                            String[] xValues = new String[size];

                            for (int i = 0; i < datas.size(); i++) {
                                BloodPressDetail.BloodPressData bloodPressData = datas.get(i);

                                String[] ss = bloodPressData.getDt().split(" ")[0].split("-");
                                xValues[i] = ss[1] + "/" + ss[2];

                                BloodPressDetail.BloodPressData.Item item = bloodPressData.getItem();
                                BloodPressDetail.BloodPressData.Item.Data high = item.getHigh();

                                HashMap<String, Object> highParams = new HashMap<>();
                                highParams.put("y", high.getAvg());
                                highParams.put("date", xValues[i]);
                                highParams.put("unit", unit);
                                highDatas[i] = highParams;

                                if (high.getMax() > highMax) {
                                    highMax = high.getMax();
                                }

                                if (high.getMin() > 0) {
                                    if (highMin == 0 || high.getMin() < highMin) {
                                        highMin = high.getMin();
                                    }
                                }

                                BloodPressDetail.BloodPressData.Item.Data low = item.getLow();

                                HashMap<String, Object> lowParams = new HashMap<>();
                                lowParams.put("y", low.getAvg());
                                lowParams.put("date", xValues[i]);
                                lowParams.put("unit", unit);
                                lowDatas[i] = lowParams;

                                if (low.getMax() > lowMax) {
                                    lowMax = low.getMax();
                                }

                                if (low.getMin() > 0) {
                                    if (lowMin == 0 || low.getMin() < lowMin) {
                                        lowMin = low.getMin();
                                    }
                                }

                                tag.add(high.getAvg() + "-" + low.getAvg());
                            }

                            tvMax.setText("本周高压：\n" + highMax + "-" + highMin + unit);
                            tvMin.setText("本周低压：\n" + lowMax + "-" + lowMin + unit);

                            buildChartView(new AASeriesElement[]{
                                    new AASeriesElement()
                                            .name("高压")
                                            .type(AAChartType.Areaspline)
                                            .lineWidth(1.5f)
                                            .marker(new AAMarker()
                                                    .symbol(AAChartSymbolType.Circle)
                                                    .radius(0f)
                                            )
                                            .color("#CF6F12")
                                            .fillColor(AAGradientColor.linearGradient(
                                                    AALinearGradientDirection.ToBottom,
                                                    new Object[][]{
                                                            {0.0, AAColor.rgbaColor(255, 164, 76, 0.6f)},//颜色字符串设置支持十六进制类型和 rgba 类型
                                                            {0.5, AAColor.rgbaColor(255, 164, 76, 0.3f)},
                                                            {1.0, AAColor.rgbaColor(255, 164, 76, 0.0f)}
                                                    }
                                            ))
                                            .data(highDatas),
                                    new AASeriesElement()
                                            .name("低压")
                                            .type(AAChartType.Areaspline)
                                            .lineWidth(1.5f)
                                            .marker(new AAMarker()
                                                    .symbol(AAChartSymbolType.Circle)
                                                    .radius(0f)
                                            )
                                            .color("#FFCC3E")
                                            .fillColor(AAGradientColor.linearGradient(
                                                    AALinearGradientDirection.ToBottom,
                                                    new Object[][]{
                                                            {0.0, AAColor.rgbaColor(255, 241, 146, 0.6f)},//颜色字符串设置支持十六进制类型和 rgba 类型
                                                            {0.5, AAColor.rgbaColor(255, 241, 146, 0.3f)},
                                                            {1.0, AAColor.rgbaColor(255, 241, 146, 0.0f)}
                                                    }
                                            ))
                                            .data(lowDatas)}, xValues, highMax, tag);
                        }
                    });
        } else {
            requestManager.request(requestManager.mJavaRetrofitService.getHealthData(RequestManager.getJsonRequestBody(params)),
                    new BaseObserverImpl<HealthDataDetail>(mContext) {
                        @Override
                        public void onSuccess(HealthDataDetail healthDataDetail) {
                            super.onSuccess(healthDataDetail);
                            String unit = "";
                            String name = "";
                            int r = 0, g = 0, b = 0;
                            String color = "";
                            if (type == 0) {
                                name = "心率";
                                unit = "bpm";
                                color = "#FF6E87";
                                r = 255;
                                g = 242;
                                b = 244;
                            } else if (type == 4) {
                                name = "血氧";
                                unit = "%";
                                color = "#46B1E9";
                                r = 70;
                                g = 177;
                                b = 233;
                            }

                            ArrayList<HealthDataDetail.HealthData> healthDataDetailDatas = healthDataDetail.getDatas();

                            int max = 0;
                            int min = 0;
                            int size = healthDataDetailDatas.size();

                            if (size > 0) {
                                setDate(healthDataDetailDatas.get(0).getDt(), healthDataDetailDatas.get(size - 1).getDt());
                            }

                            ArrayList<String> tag = new ArrayList<>();
                            Object[] datas = new Object[size];
                            String[] xValues = new String[size];
                            for (int i = 0; i < size; i++) {
                                HealthDataDetail.HealthData healthData = healthDataDetailDatas.get(i);
                                HealthDataDetail.HealthData.Item item = healthData.getItem();

                                String[] ss = healthData.getDt().split(" ")[0].split("-");
                                xValues[i] = ss[1] + "/" + ss[2];

                                tag.add(item.getAvg() + "");

                                HashMap<String, Object> params = new HashMap<>();
                                params.put("y", item.getAvg());
                                params.put("date", xValues[i]);
                                params.put("unit", unit);
                                datas[i] = params;

                                if (item.getMax() > max) {
                                    max = item.getMax();
                                }

                                if (item.getMin() > 0) {
                                    if (min == 0 || item.getMin() < min) {
                                        min = item.getMin();
                                    }
                                }
                            }

                            tvMax.setText("本周最高：\n" + max);
                            tvMin.setText("本周最低：\n" + min);


                            tvMax.append(unit);
                            tvMin.append(unit);

                            buildChartView(new AASeriesElement[]{new AASeriesElement()
                                    .name(name)
                                    .type(AAChartType.Areaspline)
                                    .lineWidth(1.5f)
                                    .marker(new AAMarker()
                                            .symbol(AAChartSymbolType.Circle)
                                            .radius(0f)
                                    )
                                    .color(color)
                                    .fillColor(AAGradientColor.linearGradient(
                                            AALinearGradientDirection.ToBottom,
                                            new Object[][]{
                                                    {0.0, AAColor.rgbaColor(r, g, b, 0.6f)},//颜色字符串设置支持十六进制类型和 rgba 类型
                                                    {0.5, AAColor.rgbaColor(r, g, b, 0.3f)},
                                                    {1.0, AAColor.rgbaColor(r, g, b, 0.0f)}
                                            }
                                    ))
                                    .data(datas)}, xValues, max, tag);
                        }
                    });
        }
    }

    private void setDate(String from, String to) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(sdf.parse(from));
            int fromMonth = calendar.get(Calendar.MONTH) + 1;
            int fromYear = calendar.get(Calendar.YEAR);
            tvDate.setText(fromYear + "年" + fromMonth + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "至");

            calendar.setTime(sdf.parse(to));
            int toYear = calendar.get(Calendar.YEAR);
            int toMonth = calendar.get(Calendar.MONTH) + 1;
            int toDay = calendar.get(Calendar.DAY_OF_MONTH);
            if (fromYear != toYear) {
                tvDate.append(toYear + "年" + toMonth + "月");
            } else {
                if (fromMonth != toMonth) {
                    tvDate.append(toMonth + "月");
                }
            }
            tvDate.append(toDay + "日");

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void buildChartView(AASeriesElement[] aaSeriesElements, String[] xValues, int max, ArrayList<String> tag) {
        AAChartModel aaChartModel = new AAChartModel()
                .categories(xValues)
                .dataLabelsEnabled(false)//是否显示值
                .xAxisLabelsEnabled(true)
                .touchEventEnabled(true)
                .stacking(AAChartStackingType.Normal)
                .yAxisVisible(true)
                .markerSymbolStyle(AAChartSymbolStyleType.InnerBlank)
                .series(aaSeriesElements);
        AAOptions aaOptions = aaChartModel.aa_toAAOptions();
        aaOptions.legend.enabled(false);
        aaOptions.xAxis.tickInterval = 3;
        AAYAxis yAxis = aaOptions.yAxis;
        aaOptions.yAxis
                .allowDecimals(false)
                .min(0F)
                .max(max == 0 ? 10F : (float) max);

        AATooltip aaTooltip = new AATooltip();
        aaTooltip.style(new AAStyle()
                .fontSize(10)
                .padding(0))
                .formatter("function () {" +
                        "let array = [];" +
                        "for(let item of this.points) {" +
                        "   let myPointOptions = item.point.options;" +
                        "   array.push(myPointOptions.date + ': ' + + myPointOptions.y + myPointOptions.unit)" +
                        "}" +
                        "return array.join('<br/>');" +
                        "}")
                .valueDecimals(2);//设置取值精确到小数点后几位//设置取值精确到小数点后几位
        aaOptions.tooltip(aaTooltip);

        aaOptions.plotOptions.series(new AASeries()
                .connectNulls(true)
                .events(new AASeriesEvents()
                        .legendItemClick(" function () {" +
                                "return false;" +
                                "}"))
        );

        aaChartView.aa_drawChartWithChartOptions(aaOptions);
        aaChartView.setTag(tag);

        tvSelectDate.setText(xValues[xValues.length - 1]);

        String unit = "";
        switch (type) {
            case 0:
                unit = "bpm";
                break;
            case 3:
                unit = "mmHg";
                break;
            case 4:
                unit = "%";
                break;
        }
        SpanUtils.with(tvData)
                .append(tag.get(tag.size() - 1)).setBold()
                .append(unit).setFontSize(12, true)
                .create();
    }
}









































